//
//  HMNetworkTools.swift
//  01-Swift网络框架封装
//
//  Created by HM on 16/5/22.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
//导入命名空间
import AFNetworking


//声明枚举
//枚举任意类型
enum HTTPMethods: Int {
    case POST
    case GET
}

struct API {
    
    static let hostName = "https://api.weibo.com/"
    
    static let loadAceessToken = "oauth2/access_token"
    
    static let loadUserInfo = "2/users/show.json"
    
    static let loadHomeData = "2/statuses/home_timeline.json"
    
    static let sendStatus = "2/statuses/update.json"

    static let sendImageStatus = "https://upload.api.weibo.com/2/statuses/upload.json"

}

class HMNetworkTools: AFHTTPSessionManager {
    //声明单例对象
    static let sharedTools: HMNetworkTools = {
        //把url前面一样的部分 声明为基础的url地址
        let url = NSURL(string: API.hostName)
        let tools = HMNetworkTools(baseURL: url)
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()

    func request(method: HTTPMethods,urlString: String, parameters: AnyObject?,finished: (responseObject: AnyObject?, error: NSError?) -> () ) {
        
        //定义闭包参数 将相同的闭包当做参数传递
        let success = { (task: NSURLSessionDataTask, result: AnyObject?) -> () in
            //执行请求成功的回调
            finished(responseObject: result, error: nil)
        }
        
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> () in
            //执行失败的回调
            finished(responseObject: nil, error: error)
        }
        
        if method == .GET {
            
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)

        } else {
            
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)

        }
    }
    
}
//获取用户信息
extension HMNetworkTools {

    func loadAccessToken(code: String, finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        let paramters = ["client_id": client_id,"client_secret": client_secret,"grant_type": "authorization_code","redirect_uri": redirect_uri,"code":code]
        
        request(.POST, urlString: API.loadAceessToken, parameters: paramters, finished: finished)
    
    }

    func loadUserInfo(response: [String: AnyObject],finished: (responseObject: AnyObject?, error: NSError?) -> ()){
    
        let token = response["access_token"]!
        
        let uid = response["uid"]!
    
        let paramters = ["access_token": token,"uid": uid]
        
        request(.GET, urlString: API.loadUserInfo, parameters: paramters, finished: finished)
    
    
    }


}
//加载首页数据

extension HMNetworkTools {

    func loadHomePageData(since_id: Int64,max_id: Int64, finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
    
        guard let token = HRUserAccountViewModel.shareAccountViewModel.userAccount?.access_token else{
        
            return
        }
        
        var parameters = ["access_token": token]
        if since_id > 0 {
        
        parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
        parameters["max_id"] = "\(max_id - 1)"
        }
        request(.GET, urlString: API.loadHomeData, parameters: parameters, finished: finished)
    
    }


}

extension HMNetworkTools {

    func sendStatus(status: String,images: [UIImage],finished: (responseObject: AnyObject?, error: NSError?) -> ()){
    
        guard let token = HRUserAccountViewModel.shareAccountViewModel.userAccount?.access_token else{
            return
        }
        let paramters = ["access_token": token,"status": status]
        print(images.count)
        if images.count > 0 {
            
           self.POST(API.sendImageStatus, parameters: paramters, constructingBodyWithBlock: { (formdata) in
            for image in images{
           
                let imageData = UIImagePNGRepresentation(image)!
            formdata.appendPartWithFileData(imageData, name: "pic", fileName: "xxoo", mimeType: "application/octet-stream")
            }
            
            
            }, progress: nil, success: { (_, result) in
                finished(responseObject: result, error: nil)
            }, failure: { (_, error) in
                finished(responseObject: nil, error: error)
           })
          
        }else {
        
         request(.POST, urlString: API.sendStatus, parameters: paramters, finished: finished)
        }
        
       
    }

}


    











